package com.common.utils;

import java.math.BigInteger;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

import com.fasterxml.jackson.databind.ObjectMapper;

import sun.misc.BASE64Decoder;

/**
 * AES加密、解密
 *
 * @author zh
 * @date 2018年3月1日
 */
public class EncryptUtil {

    //密钥 (需要前端和后端保持一致)
    private static String KEY = "lfrzzlyzjapientryp";//ConstantPropUtil.getProperty("aes_key");
    private static String IV = "012345678912qwer";//ConstantPropUtil.getProperty("aes_iv");
    //算法
    //不需向量
//    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
    //需向量
    private static final String ALGORITHMSTR = "AES/CBC/PKCS5Padding";

    private static ObjectMapper mapper = new ObjectMapper();

    /**
     * aes解密 ，采用默认秘钥及向量
     *
     * @param encrypt 内容
     * @return
     * @throws Exception
     */
    public static String aesDecrypt(String encrypt) {
        try {
            return aesDecrypt(encrypt, getDefaultKey(), getDefaultIv());
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * aes加密
     *
     * @param content
     * @return
     * @throws Exception
     */
    public static String aesEncrypt(String content) {
        try {
            return aesEncrypt(content, getDefaultKey(), getDefaultIv());
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 将对象转化为json字符串后加密
     *
     * @param obj 待转化对象
     * @return String
     */
    public static String aesEncrypt(Object obj) {
        try {
            String content = mapper.writeValueAsString(obj);
            System.out.println(content);
            return aesEncrypt(content);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 将base 64 code AES解密
     *
     * @param encryptStr 待解密的base 64 code
     * @param decryptKey 解密密钥
     * @param ivStr      向量
     * @return 解密后的string
     * @throws Exception
     */
    public static String aesDecrypt(String encryptStr, String decryptKey,
                                    String ivStr) throws Exception {
        return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey, ivStr);
    }

    /**
     * AES加密为base 64 code
     *
     * @param content    待加密的内容
     * @param encryptKey 加密密钥
     * @param ivStr      向量
     * @return 加密后的base 64 code
     * @throws Exception
     */
    public static String aesEncrypt(String content, String encryptKey,
                                    String ivStr) throws Exception {
        return base64Encode(aesEncryptToBytes(content, encryptKey, ivStr));
    }

    /**
     * base 64 encode
     *
     * @param bytes 待编码的byte[]
     * @return 编码后的base 64 code
     */
    public static String base64Encode(byte[] bytes) {
        return Base64.encodeBase64String(bytes);
    }

    /**
     * base 64 decode
     *
     * @param base64Code 待解码的base 64 code
     * @return 解码后的byte[]
     * @throws Exception
     */
    public static byte[] base64Decode(String base64Code) throws Exception {
        return StringUtils.isEmpty(base64Code) ? null : new BASE64Decoder().decodeBuffer(base64Code);
    }

    /**
     * AES加密
     *
     * @param content    待加密的内容
     * @param encryptKey 加密密钥
     * @param ivStr      向量
     * @return 加密后的byte[]
     * @throws Exception
     */
    public static byte[] aesEncryptToBytes(String content, String encryptKey,
                                           String ivStr) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        //ECB模式不需要向量
//        cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));  
        //CBC模式需要向量
        cipher.init(Cipher.ENCRYPT_MODE,
                new SecretKeySpec(encryptKey.getBytes(), "AES"),
                new IvParameterSpec(ivStr.getBytes()));
        return cipher.doFinal(content.getBytes("utf-8"));
    }

    /**
     * AES解密
     *
     * @param encryptBytes 待解密的byte[]
     * @param decryptKey   解密密钥
     * @param ivStr        向量
     * @return 解密后的String
     * @throws Exception
     */
    public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey,
                                           String ivStr) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);

        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        //ECB模式不需要向量
//        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));  
        //CBC模式需要向量
        cipher.init(Cipher.DECRYPT_MODE,
                new SecretKeySpec(decryptKey.getBytes(), "AES"),
                new IvParameterSpec(ivStr.getBytes()));
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes, "UTF-8");
    }

    /**
     * 获取默认加密秘钥
     *
     * @return String
     */
    public static String getDefaultKey() {
        if (StringUtils.isBlank(KEY)) {
            KEY = ConstantPropUtil.getProperty("aes_key");
        }
        return KEY;
    }

    /**
     * 获取默认向量
     *
     * @return String
     */
    public static String getDefaultIv() {
        if (StringUtils.isBlank(IV)) {
            IV = ConstantPropUtil.getProperty("aes_iv");
        }
        return IV;
    }

    /**
     * 将byte[]转为各种进制的字符串
     *
     * @param bytes byte[]
     * @param radix 可以转换进制的范围，从Character.MIN_RADIX到Character.MAX_RADIX，超出范围后变为10进制
     * @return 转换后的字符串
     */
    public static String binary(byte[] bytes, int radix) {
        return new BigInteger(1, bytes).toString(radix);// 这里的1代表正数  
    }

    /**
     * 测试
     */
    public static void main(String[] args) throws Exception {
        String content = "对称加密";
        Long a = System.currentTimeMillis();
        System.out.println("加密前：" + content);
        System.out.println("加密密钥和解密密钥：" + KEY);
        String encrypt = aesEncrypt(content);
        System.out.println("加密后：" + encrypt);
        String decrypt = aesDecrypt(encrypt);
        System.out.println("解密后：" + decrypt);
        Long b = System.currentTimeMillis();

        System.out.println("耗时："+(b-a));

       // String a = "RUkjrjEpzr0Jjjo0HFO9OGU9Sy38YTewbbaO73+lc4we/+31lTV+KbYJsDhSAUJlOTF3xkWXNXIpKJRYlYVIxwOyu1B0CHvawFiESxxBvfSWyhUDG3YOSx3H5/uyPWtrdro4v761rkLFPnhYECtFonU4uC5TFFER74xnFDDq5ivo12uw5Op3saSQ3O359hfBC5rWsLA6AwDe8khw4tmhxDqkFxPSxBXtS/IGUltnaakHOqW0asd1ovTP3/RaT0US/SKGAOyRl2Jsz+LnQ58Ro6ojhx8cr46A0YFZ9ElORBH8Rq8tVcKTFqFuCdCQNC55WBojkbsiFcI4Bi3MNj2aIlviqPYt4Ignbbp6cRL40DrUhMpkjEAFuz2xD1vLQi4SuSS0vtuPeNX008D5/6+D/gvQz3X1vfVLB0r3pVu+NA2JhoyqCvgDCM1wvnbrvlII3Z1L4yIRQlHUUsv9R39iOi/TPKviCi7+cWHBZaNflksmS1KMdqpE8G3mtp2qAxzCEcyp2hyN7POas2dBTWE4TnvRsEcHF8BzkFKC2Hpypm0zmCeHsJchsO4xAdLCZ9JILAdVInvxCRZ4+qcUEnKqgOASJsypuOmwySwoDYF379903PAIBdn2JNkYymz72BJHrps/ERFnjplfCSmdrh5ZHw==";
        //System.out.println(aesDecrypt(a));

    }

}
